package com.skyc.dao.impl;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import javax.sql.rowset.CachedRowSet;

import com.skyc.dao.AddressDao;
import com.skyc.dao.UserDao;
import com.skyc.entity.Address;
import com.skyc.entity.User;
import com.skyc.util.JDBCUtil;

public class AddressDaoImpl implements AddressDao{
JDBCUtil util=JDBCUtil.getJDBCUtil();
	UserDao userdao=new UserDaoImpl();
	public Address QueryById(int aid) {
		String sql="select * from t_address where a_id=?";
		CachedRowSet crs=util.query(sql, aid);
		try {
			if(crs.next()) {
				Address address=new Address();
				address.setAid(crs.getInt("a_id"));
				address.setU(userdao.queryById(String.valueOf(crs.getInt("u_id"))));
				address.setUaddress(crs.getString("u_address"));
				address.setAname(crs.getString("a_name"));
				address.setAdefault(crs.getString("a_default"));
				return address;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}finally {
			util.closeCacheRowSet(crs);
		}
		return null;
	}
	@Override
	public Address addAddress(Address address) {
		String sql="insert into t_address (u_address,a_name,a_default,u_id)values(?,?,?,?)";
		boolean flag=util.update(sql, address.getUaddress(),address.getAname(),address.getAdefault(),address.getU().getUid());
		if(flag) {
			return address;
		}
		return null;
	}
	@Override
	public List<Address> QueryByUid(User user) {
		String sql="select * from t_address where u_id=? ORDER BY a_default DESC";
		CachedRowSet crs=util.query(sql, user.getUid());
		List<Address> Addresslist=new ArrayList<Address>();
		try {
			while(crs.next()) {
				Address address=new Address();
				address.setUaddress(crs.getString("u_address"));
				address.setAname(crs.getString("a_name"));
				address.setAdefault(crs.getString("a_default"));
				address.setAid(crs.getInt("a_id"));
				address.setU(user);
				Addresslist.add(address);
			}
		} catch (SQLException e) {
			
			e.printStackTrace();
		}finally {
			util.closeCacheRowSet(crs);
		}
		return Addresslist;
	}
	@Override
	public boolean DeleteByAid(Address address) {
		String sql="DELETE  FROM t_address WHERE a_id=? ";		
		return util.update(sql, address.getAid());
	}
	@Override
	public boolean UpdateByDefault(String adefault) {
		String sql="UPDATE  t_address SET a_default='0' WHERE a_default=?";
		
		return util.update(sql, adefault);
	}
	@Override
	public boolean UpdateByAddressDefault(Address address) {
		String sql="UPDATE  t_address SET a_default='1' WHERE a_default=? and a_id=?";
		
		return util.update(sql, address.getAdefault(),address.getAid());
	}

}
